<script setup lang="ts">
import {ref, watch} from 'vue'
import {useElementSize, useWindowSize} from "@vueuse/core"

/**
 * 组件配置选项
 */
defineOptions({
  name: 'StWatchWidth',
})

/**
 * 组件参数
 */
const {
  strategy = 'self',
  widthChangeHandler = () => {},
  immediate = true,
} = defineProps<{
  // 监听组件自身宽度变化还是窗口宽度变化
  strategy?: 'self' | 'screen';
  // 宽度变化时的回调函数
  widthChangeHandler?: (width: number) => void;
  // 是否组件挂载时立即开启监听
  immediate?: boolean;
}>()

// 组件根元素引用
const stWatchWidthRef = ref<HTMLDivElement | null>(null)
// 组件根元素的宽度
const {width: stWatchWidthRefWidth} = useElementSize(stWatchWidthRef)
// 窗口的宽度
const {width: windowWidth} = useWindowSize()
// 监听宽度变化，响应式更新布局
watch(
  () => strategy === 'self' ? stWatchWidthRefWidth.value : windowWidth.value,
  (w) => widthChangeHandler(w),
  {immediate: immediate}
)
</script>

<template>
  <div
    ref="stWatchWidthRef"
    class="st-watch-width"
  >
    <slot></slot>
  </div>
</template>

<style scoped lang="scss">
.st-watch-width {
  color: inherit;
}
</style>
